const vscode = require('vscode');
const { isSameDay } = require('./utils');

// 定义 ezOne-[数字编号] 匹配的正则表达式
const ezOneRegex = /ezOne-(\d+)/g;

// 定义日期格式匹配的正则表达式 (例如 "7月15日", "12月1日")
const dateRegex = /(\d{1,2}月\d{1,2}日)/g;

// 定义“明日计划”的正则表达式，确保匹配整行
const tomorrowPlanRegex = /^(.*明日计划.*)$/gm;

// 定义高亮的样式变量
let ezOneDecorationType;
let grayLineDecorationType;
let todayLineDecorationType;
let yesterdayLineDecorationType;

/**
 * 初始化装饰器类型
 */
function initializeDecorationTypes() {
    ezOneDecorationType = vscode.window.createTextEditorDecorationType({
        textDecoration: 'underline',
        color: new vscode.ThemeColor('textLink.foreground')
    });

    grayLineDecorationType = vscode.window.createTextEditorDecorationType({
        color: new vscode.ThemeColor('input.placeholderForeground')
    });

    todayLineDecorationType = vscode.window.createTextEditorDecorationType({
        color: new vscode.ThemeColor('input.placeholderForeground'),
        after: {
            contentText: ' 今天',
            color: new vscode.ThemeColor('terminal.ansiGreen'),
            margin: '0 0 0 1em'
        }
    });

    yesterdayLineDecorationType = vscode.window.createTextEditorDecorationType({
        color: new vscode.ThemeColor('input.placeholderForeground'),
        after: {
            contentText: ' 昨天',
            color: new vscode.ThemeColor('terminal.ansiRed'),
            margin: '0 0 0 1em'
        }
    });
}

/**
 * 更新所有 ezOne ID 和日期的装饰器
 */
function updateDecorations() {
    const editor = vscode.window.activeTextEditor;

    if (!editor || editor.document.languageId !== 'markdown') {
        // 语言不匹配时，清理并释放装饰器
        disposeDecorations();
        return;
    }

    // 确保装饰器类型已初始化
    if (!ezOneDecorationType) {
        initializeDecorationTypes();
    }

    const text = editor.document.getText();
    const ezOneMatches = [];
    const grayRanges = new Set();
    const todayRanges = [];
    const yesterdayRanges = [];

    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const yesterday = new Date(today);
    yesterday.setDate(today.getDate() - 1);

    // 匹配 ezOne ID
    let match;
    ezOneRegex.lastIndex = 0;
    while ((match = ezOneRegex.exec(text))) {
        const [fullMatch] = match;
        const startPos = editor.document.positionAt(match.index);
        const endPos = editor.document.positionAt(match.index + fullMatch.length);
        ezOneMatches.push({ range: new vscode.Range(startPos, endPos) });
    }

    // 统一处理日期和“明日计划”的行高亮
    const allLinesToProcess = new Map();

    // 匹配日期所在的行
    dateRegex.lastIndex = 0;
    while ((match = dateRegex.exec(text))) {
        const line = editor.document.lineAt(editor.document.positionAt(match.index).line);
        allLinesToProcess.set(line.lineNumber, line.range);
    }

    // 匹配“明日计划”所在的行
    tomorrowPlanRegex.lastIndex = 0;
    while ((match = tomorrowPlanRegex.exec(text))) {
        const line = editor.document.lineAt(editor.document.positionAt(match.index).line);
        allLinesToProcess.set(line.lineNumber, line.range);
    }

    // 遍历所有需要处理的行，进行分类
    allLinesToProcess.forEach(range => {
        const lineText = editor.document.getText(range);
        let handled = false;

        // 检查是否包含日期
        const dateMatch = dateRegex.exec(lineText);
        if (dateMatch) {
            const dateString = dateMatch[0];
            const currentYear = new Date().getFullYear();
            const parsedDateStr = `${currentYear}/${dateString.replace('月', '/').replace('日', '')}`;
            let docDate = new Date(parsedDateStr);

            if (!isNaN(docDate.getTime())) {
                docDate.setHours(0, 0, 0, 0);

                if (isSameDay(docDate, today)) {
                    todayRanges.push({ range });
                    handled = true;
                } else if (isSameDay(docDate, yesterday)) {
                    yesterdayRanges.push({ range });
                    handled = true;
                }
            }
        }

        // 如果没有被“今天”或“昨天”高亮，则检查是否是“明日计划”或普通灰色日期
        if (!handled) {
            if (tomorrowPlanRegex.test(lineText)) {
                grayRanges.add(range);
            } else if (dateMatch && isNaN(new Date(`${new Date().getFullYear()}/${dateMatch[0].replace('月', '/').replace('日', '')}`).getTime())) {
                grayRanges.add(range);
            } else if (dateMatch) {
                grayRanges.add(range);
            }
        }
        // 重置正则的lastIndex，以便下次循环正确匹配
        dateRegex.lastIndex = 0;
        tomorrowPlanRegex.lastIndex = 0;
    });

    // 应用装饰器
    editor.setDecorations(ezOneDecorationType, ezOneMatches);
    editor.setDecorations(grayLineDecorationType, Array.from(grayRanges).map(range => ({ range })));
    editor.setDecorations(todayLineDecorationType, todayRanges);
    editor.setDecorations(yesterdayLineDecorationType, yesterdayRanges);
}

/**
 * 停用时清理装饰器资源
 */
function disposeDecorations() {
    [ezOneDecorationType, grayLineDecorationType, todayLineDecorationType, yesterdayLineDecorationType].forEach(type => {
        type?.dispose();
    });
    // 清空引用，以便下次 activate 时重新初始化
    ezOneDecorationType = undefined;
    grayLineDecorationType = undefined;
    todayLineDecorationType = undefined;
    yesterdayLineDecorationType = undefined;
}

module.exports = {
    updateDecorations,
    disposeDecorations
};